import puppeteer from 'puppeteer';
import fs from 'fs';
import './p1_1-cityPinyin.mjs'
import toPinyin from "./p1_1-cityPinyin.mjs";
(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('http://lishi.tianqi.com/');

    // Type into search box.
    await page.type('#city-Z > td > ul > li:nth-child(57) > a', 'Headless Chrome');

    const resultsSelector = '.table_list > li > a';
    await page.waitForSelector(resultsSelector);

    // Extract the results from the page.
    const links = await page.evaluate(resultsSelector => {
        return [...document.querySelectorAll(resultsSelector)].map(anchor => {
            return `${anchor.text} - ${anchor.href}`;
        });
    }, resultsSelector);

    await browser.close();

    // 输出到文件
    let data = links.join("\n");
    fs.writeFile("cities.txt", data,(error)=>{
        if(error){
            console.error(error);
        } else {
            console.log("文件写入完成");
        }
    })

    // 缓存城市的拼音
    toPinyin(data);

})();